<template>
  <div class="table-search">
    <el-popover
      ref="popover"
      v-model="popoverVisible"
      placement="bottom-start"
      :width="advancedWidth"
    >
      <slot name="advanced-content" />
      <div style="text-align: right; margin: 0">
        <el-popover
          v-model="visible_del_popover"
          placement="top"
          width="160"
        >
          <p>确定要清空表单吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button :size="size" type="text" @click="visible_del_popover = false">取消</el-button>
            <el-button type="primary" :size="size" @click="handleCleanForm">确定</el-button>
          </div>
          <el-button slot="reference" :size="size" type="text" class="clean-form">清空</el-button>
        </el-popover>
        <el-button :size="size" type="text" @click="popoverVisible = false">取消</el-button>
        <el-button type="primary" :size="size" @click="advancedSearch">确定</el-button>
      </div>
      <slot slot="reference" name="reference" />
    </el-popover>
  </div>
</template>

<script>
export default {
  name: 'TableSearch',
  props: {
    advancedWidth: {
      type: Number,
      default: 405
    },
    placeholder: {
      type: String,
      default: '请输入关键字'
    }
  },
  data() {
    return {
      popoverVisible: false,
      visible_del_popover: false,
      clearFuncs: [],
      clearFuncNames: ['clearValue', 'deleteSelected']
    }
  },
  computed: {
    size() {
      return this.$store.state.app.size
    }
  },
  methods: {
    /** 高级搜索 */
    advancedSearch() {
      this.visible_del_popover = false
      this.popoverVisible = false
      this.$emit('advancedSearch', {})
    },
    /** 清空表单 */
    handleCleanForm(event) {
      let $parent = this.$parent.$parent
      if (!this.$parent.$parent.$refs['advancedForm']) {
        $parent = this.$parent.$parent.$parent.$parent
      }
      const $form = $parent.$refs['advancedForm']
      const objs = JSON.parse(JSON.stringify($parent.queryForm))
      Object.keys(objs).forEach(key => {
        if (key !== 'pageNum' && key !== 'pageSize') $parent.queryForm[key] = ''
      })
      this.findClearValue($form)
      this.clearFuncs.forEach(func => func(event))
      this.clearFuncs = []
      this.visible_del_popover = false
    },
    /** 递归查找组件清空的方法 */
    findClearValue(component) {
      const { clearFuncs, clearFuncNames } = this
      const { $children: $ch } = component
      $ch && $ch.length && $ch.forEach(item => {
        const funs = clearFuncNames.filter(name => typeof item[name] === 'function')
        if (funs.length) {
          clearFuncs.push(item[funs[0]])
        } else {
          this.findClearValue(item)
        }
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
  .clean-form {
    color: #F56C6C;
    margin-right: 10px;
  }

  .clean-form:hover, .clean-form:visited {
    color: #F56C6C;
  }
</style>
